<template>
  <div class="padding" v-loading.fullscreen.lock="fullscreenLoading">
    <el-card class="margin-bottom">
      <el-row :gutter="30" type="flex">
        <el-col :span="4">
          <span class="title-icon">合单应收应付</span>
        </el-col>
        <el-col :span="3">
          <span
            >体积(CBM):{{ towNumber(Constatvariable["inStockVolume"]) }}</span
          >
        </el-col>
        <el-col :span="3">
          <span
            >计费重:{{
              towNumber(Constatvariable["inStockChargedWeight"])
            }}</span
          >
        </el-col>
        <el-col :span="3" v-if="initOptionsData.serviceCompanyMap">
          <span
            >服务商:{{
              initOptionsData.serviceCompanyMap[
                Constatvariable["serviceCompanyId"]
              ]
            }}</span
          >
        </el-col>
        <el-col :span="7" v-if="initOptionsData.serviceCompanyMap">
          <span
            >清关服务商:{{
              initOptionsData.serviceCompanyMap[
                Constatvariable["customsClearanceAgent"]
              ]
            }}</span
          >
        </el-col>
        <el-col :span="4" class="text-right"> </el-col>
        <!-- <el-col :span="4">
          <el-button
            style="margin-right:85px;"
            v-if="Constatvariable['status'] && Constatvariable['status'] != 999"
            type="text"
            size="mini"
            class="header-save-btn"
            @click="allocationWaybillMegerPay"
          >
            合单分配费用
          </el-button>
        </el-col> -->
      </el-row>
    </el-card>
    <el-card class="margin-bottom">
      <div slot="header" class="clearfix relative">
        <span class="title-icon">总计</span>
        <span>
          &nbsp;&nbsp;&nbsp;投保金额：{{
            Constatvariable["serviceInsuranceFee"]
          }}</span
        >
      </div>
      <el-row style="border-bottom:1px solid #ccc" class="padding-bottom-sm">
        <el-col :span="6"
          ><span class="text-bold">应收总计：</span>{{ receiveTotalCost }}
          {{ standardCurrency }}</el-col
        >
        <el-col :span="6"
          ><span class="text-bold">应付总计：</span>{{ payTotalCost }}
          {{ standardCurrency }}</el-col
        >
        <el-col :span="6"
          ><span class="text-bold">利润：</span>{{ totalProfit }}
          {{ standardCurrency }}</el-col
        >
        <el-col :span="6"
          ><span class="text-bold">利润率：</span> {{ totalProfitD }}</el-col
        >
      </el-row>
      <div style="border-bottom:1px solid #ccc">
        <div class="text-bold padding-tb-sm">
          合单应付汇总：
        </div>

        <el-row class="row-item">
          <el-col :span="6" v-for="(item, k) in payMap" :key="k">
            {{ k }}：
            <span v-for="(m, n) in item" :key="m" :value="n">
              {{ m }} {{ n }}
            </span>
          </el-col>
        </el-row>
      </div>
      <div style="border-bottom:1px solid #ccc">
        <div class="text-bold padding-tb-sm">
          运单应收汇总：
        </div>
        <el-row class="row-item">
          <el-col :span="6" v-for="(item, k) in receiveMap" :key="k">
            {{ k }}：
            <span v-for="(m, n) in item" :key="m" :value="n">
              {{ m }} {{ n }}
            </span>
          </el-col>
        </el-row>
      </div>
      <div>
        <div class="text-bold padding-tb-sm">
          运单应付汇总：
        </div>

        <el-row class="row-item">
          <el-col :span="6" v-for="(item, k) in mergePayMap" :key="k">
            {{ k }}：
            <span v-for="(m, n) in item" :key="m" :value="n">
              {{ m }} {{ n }}
            </span>
          </el-col>
        </el-row>
      </div>
    </el-card>

    <el-collapse v-model="activeNames" class="margin-bottom">
      <el-collapse-item class="margin-bottom" name="Receivable">
        <template slot="title">
          <el-row style="width:100%" class="padding-lr">
            <span class="title-icon">应收</span>
          </el-row>
        </template>
        <el-card class="margin-bottom">
          <el-table
            size="mini"
            ref="multipleTable"
            :data="receivableData"
            style="width: 100%"
            @selection-change="handleSelectionChange"
            ><ex-table-column
              v-for="item in tabColumns"
              :key="item.prop"
              :prop="item.prop"
              :label="item.label"
              :autoFit="true"
              :fitHeader="true"
            >
              <template slot-scope="scope">
                <template v-if="item.prop === 'billingDate'">
                  <span
                    v-if="scope.row[item.prop] === null"
                    class="fa fa-calendar-alt text-lg pointer"
                  ></span>

                  <el-popover
                    v-else
                    placement="right"
                    trigger="hover"
                    @show="getBillingDate(scope, 0)"
                  >
                    {{ scope.row[item.prop] }}
                    <span
                      slot="reference"
                      class="fa fa-calendar-alt text-lg pointer"
                    ></span>
                  </el-popover>
                </template>
                <template v-else>
                  {{ scope.row[item.prop] }}
                </template>
              </template>
            </ex-table-column>
          </el-table>
        </el-card>
      </el-collapse-item>
    </el-collapse>

    <div v-if="loadingOver" class="padding-tb-sm">
      <el-row>
        <el-col :span="6">
          <span style="margin-left:20px;" class="title-icon"
            >服务商账单导入：请先选择服务商</span
          >
        </el-col>
        <el-col :span="4" v-if="parseServicerMap">
          <el-select
            v-model="parseServicerId"
            @change="chnageUpload"
            placeholder="请选择类型"
            filterable
            clearable
            size="mini"
            :style="{ width: '100%' }"
          >
            <el-option
              v-for="(k, v) in parseServicerMap"
              :key="k"
              :label="parseServicerMap[v]"
              :value="parseInt(v)"
            ></el-option>
          </el-select>
        </el-col>
      </el-row>
    </div>
    <el-card v-if="uploadShow">
      <el-upload
        class="upload-demo"
        ref="upload"
        drag
        action="fakeaction"
        :show-file-list="true"
        :http-request="uploadFn"
        :on-preview="handlePreview"
        :on-remove="handleRemove"
        :auto-upload="false"
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div slot="tip" class="el-upload__tip"></div>
      </el-upload>
      <el-button
        style="margin-left: 10px;"
        size="small"
        type="success"
        @click="submitUpload"
        v-loading.fullscreen.lock="fullscreenLoading"
        >上传到服务器</el-button
      >
    </el-card>
    <el-card>
      <div slot="header" class="clearfix relative">
        <span class="title-icon">应付</span>
        <span
          v-if="isChangePayable"
          class="text-blue margin-left-sm"
          @click="selectAll"
          >{{ selectAllStatus ? "全不选" : "全选" }}</span
        >

        <el-button
          style="margin-right:125px;"
          type="text"
          size="mini"
          class="header-save-btn"
          @click="addPayable"
        >
          新增
        </el-button>
        <el-button
          style="margin-right:165px;"
          type="text"
          size="mini"
          class="header-save-btn"
          @click="copyPaymentinfo"
        >
          <el-tooltip effect="light" placement="bottom" content="复制应付">
            <i class="el-icon-document-copy" style="font-size:20px"></i>
          </el-tooltip>
        </el-button>
        <el-button
          size="mini"
          type="success"
          class="header-save-btn"
          @click="saveReceivable"
        >
          保存
        </el-button>
      </div>

      <HotTable
        ref="hotTable"
        :templateName="`Receivable`"
        :templateData.sync="payableData"
        :verifyShow="verifyShow"
        :templateOptUser="optUser"
        :payToReceve.sync="receivableData"
        :templateOptions="templateOptions"
        :templateType="`mergepayable`"
        :templateDelPayIds="delPayIds"
        @getInfo="lazyloadWaybillReceivePayables"
        class="margin-top text-sm"
      ></HotTable>
    </el-card>

    <CopyPayment
      ref="CopyPayment"
      :payableData.sync="payableData"
      :templateType="`mergepayable`"
    ></CopyPayment>

    <el-dialog title="标记分配单号" :visible.sync="signDialog">
      <el-table
        :data="singleMap"
        size="mini"
        ref="selectTable"
        class="text-sm"
        :key="1"
        row-key="key"
        default-expand-all
        @select-all="handleAllSelection"
        @select="(selection, row) => handleSelectionChange2(selection, row)"
        :tree-props="{ children: 'children' }"
        max-height="500"
      >
        <el-table-column type="selection" width="25" :selectable="seleDeclarectable"></el-table-column>
        <el-table-column label="" prop="waybillNo">
          <template slot-scope="scope">
            <template v-if="scope.row.isChild">
              {{ scope.row.waybillNo }}({{
                scope.row.isTaxFarming ? "包税" : "不包税"
              }})
            </template>
            <template v-else>
              {{ scope.row.waybillNo }}
            </template>
          </template>
        </el-table-column>
        <el-table-column label="客户名称">
          <template slot-scope="scope">
            <template v-if="scope.row.isChild">
              {{ initOptionsData["customerMap"][scope.row.customerId] }}
            </template>
          </template>
        </el-table-column>
        <el-table-column label="派送方式">
          <template slot-scope="scope">
            <template v-if="scope.row.isChild">
              <template
                v-if="
                  (scope.row.trackNumber && scope.row.trackNumber) ||
                    (scope.row.trackNumber2 && scope.row.trackNumber2) ||
                    (scope.row.trackNumber3 && scope.row.trackNumber3)
                "
              >
                <div>快递派送</div>
              </template>

              <template v-else>
                <div>卡车派送</div>
              </template>
            </template>
          </template>
        </el-table-column>
        <el-table-column
          label="仓库地址"
          prop="dispatchAddressCode"
        ></el-table-column>
      </el-table>
      <div slot="footer">
        <el-button size="mini" type="primary" @click="saveSign">确定</el-button>
      </div>
    </el-dialog>

    <div v-if="singleList.length > 0">
      <el-card
        class="margin-top"
        v-for="(item, index) in singleList"
        :key="index"
      >
        <div slot="header">
          <el-button size="mini" type="danger" @click="revoke(index)"
            >撤销</el-button
          >
          <span class="text-sm margin-lr">H单号：{{ item.HNumber }}</span>
          <span class="text-sm">运单号：{{ item.waybillNoList }}</span>
        </div>
        <el-table
          :data="item.tableData"
          class="text-sm"
          size="mini"
          :show-header="false"
          @selection-change="handleSelectionSingle($event, index)"
        >
          <ex-table-column :autoFit="true" type="selection"></ex-table-column>
          <ex-table-column :autoFit="true" prop="serCusId"></ex-table-column>
          <ex-table-column :autoFit="true" prop="costName"></ex-table-column>
          <ex-table-column
            :autoFit="true"
            prop="costNameType"
          ></ex-table-column>
          <ex-table-column
            :autoFit="true"
            prop="configPayTypec"
          ></ex-table-column>
          <ex-table-column :autoFit="true" prop="count"></ex-table-column>
          <ex-table-column :autoFit="true" prop="unitPrice"></ex-table-column>
          <ex-table-column :autoFit="true" prop="currency"></ex-table-column>
          <ex-table-column :autoFit="true" prop="totalCost"></ex-table-column>
          <ex-table-column :autoFit="true" prop="remain"></ex-table-column>
          <ex-table-column :autoFit="true" prop="billType"></ex-table-column>
          <ex-table-column
            :autoFit="true"
            prop="responsibleId"
          ></ex-table-column>
          <ex-table-column :autoFit="true" prop="accountDate"></ex-table-column>
          <ex-table-column :autoFit="true" prop="remark"></ex-table-column>
        </el-table>
      </el-card>
    </div>
  </div>
</template>

<script>
import { ajax } from "@/store/yg/common/utils";
import axios from "axios";
import * as constant from "@/store/yg/common/constant";
import { untransform } from "@/store/yg/common/uri";
import { clone } from "@/utils/clone";
import HotTable from "./../../alledit/components/HotTable";
import CopyPayment from "./../../alledit/components/CopyPayment";
import { m } from "@/store/yg/common/local";
import { CollapseItem } from "element-ui";
import { parseTime, randomRange } from "@/utils";

export default {
  components: {
    HotTable,
    CopyPayment
  },
  props: {
    Constatvariable: {
      type: Object,
      default: function() {
        return {};
      }
    },
    initOptionsData: {
      type: Object,
      default: function() {
        return {};
      }
    },
    verifyShow: {
      type: Object,
      default: function() {
        return {};
      }
    }
  },
  data() {
    return {
      //快递总毛重
      totalProfitD: 0,
      // 分单号
      singleList: [],
      singleMap: [],
      //报关运单id :运单号
      declarationMap: {},
      //报关运单集合
      declarations: [],
      activeNames: [],
      totalexpressweight: "",
      collectMap: {},
      fullscreenLoading: false,
      showSign: false,
      signDialog: false,
      list: {},
      listData: [],
      signData: [],
      tableData: [],
      templateOptions: {
        //C类
        paycOptions: ["C0", "C1", "C2", "C3"],
        //账单类型
        options: ["起", "目"],
        //币种
        currencyOptions: [],
        //费用名称：
        configPayNameOptions: [],
        //费用类型
        configPayTypeOptions: [],
        //用户信息
        userOptions: [],
        // 应收对应客户
        companyOptions: [],
        // 应付对应服务商
        serviceOptions: [],
        payNameTypeMap: {}
      },
      loadingOver: false,
      //当前用户
      optUser: "",
      //记录应收删除的ID
      delReceveIds: [],
      //记录应付删除的ID
      delPayIds: [],
      //应收
      receiveTotalCost: 0,
      //应付
      payTotalCost: 0,
      //利润率
      profit: "0%",
      //应付信息
      payMap: {},
      //应收信息
      receiveMap: {},
      mergePayMap: {},
      standardCurrency: "RMB",
      restaurants: [],
      selectionList: [],
      selectionPayableList: [],
      isChangeReceivable: false,
      isChangePayable: false,
      //服务商解析管理
      parseServicerMap: {},
      totalProfit: 0,
      tabColumns: [
        { prop: "serCusId", label: "公司" },
        { prop: "costName", label: "费用名称" },
        { prop: "costNameType", label: "类型" },
        { prop: "configPayTypec", label: "C类" },
        { prop: "responsibleId", label: "责任人" },
        { prop: "count", label: "数量" },
        { prop: "unitPrice", label: "单价" },
        { prop: "currency", label: "币种" },
        { prop: "totalCost", label: "总额" },
        { prop: "remain", label: "余额" },
        { prop: "billType", label: "账单类型" },
        { prop: "inputUser", label: "录入人" },
        { prop: "lastModifier", label: "修改人" },
        { prop: "remark", label: "备注" },
        { prop: "accountDate", label: "费用日期" },
        { prop: "billingDate", label: "销账日期" },
        { prop: "cdate", label: "创建日期" }
      ],
      tabColumns2: [
        { prop: "serCusId", label: "公司" },
        { prop: "costName", label: "费用名称" },
        { prop: "costNameType", label: "类型" },
        { prop: "configPayTypec", label: "C类" },
        { prop: "responsibleId", label: "责任人" },
        { prop: "count", label: "数量" },
        { prop: "unitPrice", label: "单价" },
        { prop: "currency", label: "币种" },
        { prop: "totalCost", label: "总额" },
        { prop: "remain", label: "余额" },
        { prop: "billType", label: "账单类型" },
        { prop: "isAllocated", label: "是否分配" },
        { prop: "inputUser", label: "录入人" },
        { prop: "lastModifier", label: "修改人", type: "boolean" },
        { prop: "remark", label: "备注" },
        { prop: "accountDate", label: "费用日期" },
        { prop: "billingDate", label: "销账日期" },
        { prop: "cdate", label: "创建日期" }
      ],
      receivableData: [],
      payableData: [],
      shippingWay: "",
      action: "",
      feeData: [],
      fileList: [{ name: "", url: "" }],
      uploadShow: false,
      parseServicerId: "",
      selectAllStatus: false,
      selectWaybillInfoList: [],
      booleanSeleDeclarectable: false,
      selectedList: []
    };
  },

  methods: {
    handleSelectionSingle(e, index) {
      // console.log("e :>> ", e);
      // console.log("index :>> ", index);
      this.singleList[index].selecteds = e;
    },
    towNumber(val) {
      if (val && val != null) {
        return val.toFixed(3);
      } else {
        return 0;
      }
    },
    saveReceivable() {
      for (var [i, e] of this.payableData.entries()) {
        e.waybillId = this.$route.query.waybillId;
        if (!this.checkRule(e, i)) break;
      }
      this.allocationWaybillMegerPay();
    },
    selectAll() {
      this.selectAllStatus = !this.selectAllStatus;
      const data = clone(this.payableData);
      this.payableData = [];
      for (const i of data) {
        if (this.selectAllStatus) {
          i.selectStatus = true;
        } else {
          i.selectStatus = false;
        }
      }
      this.payableData = data;
    },
    /**分配应收应付 */
    allocationWaybillMegerPay() {
      var param = {};
      param["headers"] = {
        "YG-UNIQUE-KEY": "save_" + new Date().getTime()
      };
      param["waybillId"] = this.$route.query.waybillId;
      param["lmAllocation"] = 0;
      if (this.shippingWay && this.shippingWay == "P") {
        console.log("物流方式", this.shippingWay);
        param["lmAllocation"] = 1;
        // this.$message.error("小包功能暂未开放!");
        // return;
      }
      let waybillReceivePayables = [];
      // if (this.singleList.length > 0) {
      //   this.payableData.forEach(element => {
      //     if (element.selectStatus) {
      //       waybillReceivePayables.push(element);
      //     }
      //   });
      // } else {
      //   waybillReceivePayables = this.payableData;
      // }
      waybillReceivePayables = clone(this.payableData);
      const lumpMap = {};
      for (const i of this.singleList) {
        console.log("i :>> ", i);
        if (
          i.lumpName &&
          i.lumpName != null &&
          i.lumpName.indexOf("declare") > -1
        ) {
          console.log("关税重新生成：", i.lumpName);
          lumpMap[i.lumpName] = this.declarations.join();
        } else {
          lumpMap[i.lumpName] = i.waybillNoList;
        }
        //lumpMap[i.lumpName] = i.waybillNoList;
      }
      var checkC = false;
      waybillReceivePayables.forEach(element => {
        if (element.id == null && element.costName === "关税") {
          const lumpName = "declare" + this.guid();
          element.lumpName = lumpName;
          lumpMap[lumpName] = this.declarations.join();
          console.log("这是个新增的关税：", element.costName, lumpName);
        }
        if (element.costNameType === "C") {
          if (!element.configPayTypec || element.configPayTypec === "") {
            checkC = true;
            return;
          }
        }
      });
      if (checkC) {
        this.$message.error("请选择C类!");
        return;
      }
      param["delPayIds"] = this.delPayIds;
      param["lumpMap"] = lumpMap;
      param["waybillReceivePayables"] = waybillReceivePayables;
      console.log(param);
      this.fullscreenLoading = true;
      ajax("allocationWaybillMegerPay", param).then(
        res => {
          if (res.code != 200) {
            this.fullscreenLoading = false;
            if (null != res.message) {
              this.$message.error(m(res.message));
            } else {
              this.$message.error("分配失败!");
            }
          } else {
            this.$message.success("分配成功!");
            setTimeout(() => {
              this.fullscreenLoading = false;
              this.lazyloadWaybillReceivePayables();
            }, 10000);
          }
        },
        error => {
          console.log(error);
        }
      );
    },
    seleDeclarectable(row,index) {
      //通过某个值来进行判断，规定那一行的选择框被禁用

      if (this.booleanSeleDeclarectable && (!row.isTaxFarming ||  row.isTaxFarming == 0)) {
        return false;
      }
      return true;
    },
    sign() {
      const arr = [];
      for (const [i, e] of this.payableData.entries()) {
        if (e.selectStatus && !e.disabled) {
          // e.disabled = true;
          e.flag = randomRange(6, 20);
          arr.push(e);
        }
      }
      this.listData = arr;
      console.log("this.listData :>> ", this.listData);
      if (this.listData.length) {
        if (this.listData.length ===1 && this.listData[0].costName =='关税') {
            console.log('选择了一条关税');
            this.$message.warning("当前选择关税分配，已禁止分配不包税运单");
            this.booleanSeleDeclarectable = true;
        }


        this.signDialog = true;
      } else {
        this.$message.warning("请先选择应付费用");
      }
    },
    saveSign() {
      // if (this.selectWaybillInfoList) {
      //   return
      // }

      const lumpName = this.guid();

      if (this.selectedList.length === 0) {
        this.$message.warning("请先选择单号");
        return;
      }
      this.signDialog = false;

      // const td = this.$refs.hotTable.$el.children[0].children[0].children[0]
      //   .children[0].children[0].children[0].children[2].children;
      for (const [i, e] of this.listData.entries()) {
        if (e.selectStatus) {
          e.lumpName = lumpName;
          e.disabled = true;
          // td[i].children[0].children[0].setAttribute("disabled", true);
        }
      }
      this.$refs.hotTable.$refs.hotTable.hotInstance.loadData(this.payableData);

      const arr = [];
      let waybillSingleNo = "";
      for (const i of this.selectedList) {
        arr.push(i.waybillNo);
        waybillSingleNo = i.waybillSingleNo || "";
      }
      const obj = {
        waybillNoList: arr.join(),
        HNumber: waybillSingleNo,
        lumpName: lumpName,
        tableData: this.listData
      };
      this.singleList.push(obj);
      this.selectedList = [];
      for (const i of this.singleMap) {
        this.$delete(i, "isSel");
        this.$set(i, "isSel", false);
        for (const j of i.children) {
          this.$delete(j, "isSel");
          this.$set(j, "isSel", false);
        }
      }
    },
    revoke(index) {
      console.log("index :>> ", index);
      console.log("this.singleList[index] :>> ", this.singleList[index]);
      if (
        !this.singleList[index].selecteds ||
        this.singleList[index].selecteds.length === 0
      ) {
        this.$message.error("请选择要撤销的数据！");
        return;
      }

      this.$confirm("是否确认撤销？")
        .then(() => {

          const td = this.$refs.hotTable.$el.children[1].children[0].children[0]
            .children[0].children[0].children[0].children[2].children;
          // 全删
          if (
            this.singleList[index].selecteds.length ===
            this.singleList[index].tableData.length
          ) {
            console.log("全删 :>> ");
            const arr = this.singleList.splice(index, 1);
            const list = [];
            for (const i of arr[0].tableData) {
              list.push(i.lumpName);
            }

            for (const [j, e] of this.payableData.entries()) {
              if (list.includes(e.lumpName)) {
                e.selectStatus = false;
                e.disabled = false;
                e.lumpName = "";
                td[j].children[0].children[0].setAttribute("disabled", false);
              }
            }
            this.$refs.hotTable.$refs.hotTable.hotInstance.loadData(
              this.payableData
            );
          } else {
            console.log("不全删 :>> ");
            for (const i of this.singleList[index].selecteds) {
              const tag = this.singleList[index].tableData.findIndex(
                x => x.id === i.id
              );
              console.log("tag :>> ", tag);
              if (tag !== -1) {
                this.singleList[index].tableData.splice(tag, 1);
                console.log("this.payableData :>> ", this.payableData);
                console.log("i.flag :>> ", i.flag);
                const tag2 = this.payableData.findIndex(x => x.flag === i.flag);
                console.log("tag2 :>> ", tag2);
                if (tag2) {
                  this.$delete(this.payableData[tag2], "selectStatus");
                  this.$delete(this.payableData[tag2], "disabled");
                  this.$delete(this.payableData[tag2], "lumpName");
                  this.$set(this.payableData[tag2], "selectStatus", false);
                  this.$set(this.payableData[tag2], "disabled", false);
                  this.$set(this.payableData[tag2], "lumpName", "");
                  td[tag2].children[0].children[0].setAttribute(
                    "disabled",
                    false
                  );
                }
              }
            }
          }
        })
        .catch(() => {});
    },
    pushReceiveToCustomer() {
      var param = {};
      ajax("pushReceiveToCustomer", param).then(
        res => {
          if (res.code != 200) {
            if (null != res.message) {
              this.$message.error(m(res.message));
            } else {
              this.$message.error("推送失败!");
            }
          } else {
            this.$message.success("推送成功!");
          }
        },
        error => {
          console.log(error);
        }
      );
    },

    copyPaymentinfo() {
      this.$refs.CopyPayment.centerDialogVisible = true;
    },
    copyReceivableinfo() {
      this.$refs.CopyReceivable.centerDialogVisible = true;
    },
    chnageUpload() {
      this.uploadShow = true;
    },
    uploadFn(params) {
      //自定义上传文件

      const file = params.file,
        fileType = file.type,
        isImage = fileType.indexOf("pdf") !== -1,
        isLt4M = file.size / 1024 / 1024 < 4;
      // 这里常规检验，看项目需求而定
      // if (!isImage) {
      //  this.$message.error("只能上传pdf格式!");
      //  return;
      // }

      //if (!isLt4M) {
      //   this.$message.error("只能上传图片大小小于4M");
      //   return;
      //  }
      // 根据后台需求数据格式
      if (this.parseServicerId === null || "" === this.parseServicerId) {
        this.$message.error("请选择服务商");
        return;
      }

      const form = new FormData();
      // 文件对象

      form.append("items[]", file);
      form.append("servicerParseId", this.parseServicerId);
      form.append("waybillId", this.$route.query.waybillId);
      this.fullscreenLoading = true;
      axios({
        method: "post",
        url: this.action,
        data: form
      })
        .then(response => {
          this.$refs["upload"].clearFiles();
          this.fullscreenLoading = false;
          if (response.data.code === 200) {
            this.feeData.push({
              mes: response.data.data.fileName,
              fee: response.data.data.fullFileName
            });
            this.lazyloadWaybillReceivePayables();
          } else {
            this.$notify.error({
              title: "错误",
              message: "上传失败!" + response.data.message
            });
          }
        })
        .catch(error => {
          console.log(error);
          this.$notify.error({
            title: "错误",
            message: "上传失败!"
          });
        });
    },

    selectWaybillInfo(val) {
      console.log(
        "%cval: ",
        "color: MidnightBlue; background: Aquamarine;",
        val
      );
      this.selectWaybillInfoList = val;
    },
    handleSelectionChange(val) {
      console.log(
        "%cval: ",
        "color: MidnightBlue; background: Aquamarine;",
        val
      );
      this.selectionList = val;
    },
    addReceivable() {
      console.log("this.templateOptions :>> ", this.templateOptions);

      var receive = {
        id: "",
        serCusId: this.initOptionsData["customerMap"][
          this.Constatvariable.customerId
        ],
        costName: "",
        costNameType: "",
        configPayTypec: "",
        responsibleId: "",
        inputUser: this.optUser,
        lastModifier: this.optUser,
        unitPrice: "",
        count: "",
        currency: "",
        totalCost: "",
        remain: "",
        billType: "",
        amoebaSubjectId: "",
        accountDate: parseTime(new Date().toLocaleDateString(), "{y}-{m}-{d}"),
        cdate: parseTime(new Date().toLocaleDateString(), "{y}-{m}-{d}"),
        remark: ""
      };
      this.receivableData.push(receive);
    },
    addPayable() {
      var payble = {
        id: "",
        serCusId: "",
        costName: "",
        costNameType: "",
        configPayTypec: "",
        responsibleId: "",
        inputUser: this.optUser,
        lastModifier: this.optUser,
        unitPrice: "",
        count: "",
        currency: "",
        totalCost: "",
        remain: "",
        billType: "",
        amoebaSubjectId: "",
        accountDate: parseTime(new Date().toLocaleDateString(), "{y}-{m}-{d}"),
        cdate: parseTime(new Date().toLocaleDateString(), "{y}-{m}-{d}"),
        remark: ""
      };
      this.payableData.push(payble);
    },
    payableSelectionChange(val) {
      this.selectionPayableList = val;
    },
    changeReceivable() {
      if (this.isChangeReceivable) {
        let flag = true;
        for (var [i, e] of this.receivableData.entries()) {
          e.waybillId = this.$route.query.waybillId;
          flag = this.checkRule(e, i);
        }
        if (!flag) {
          return;
        }
        this.fullscreenLoading = true;
        ajax("saveWaybillReceiveBaseInfo", this.receivableData).then(
          res => {
            this.fullscreenLoading = false;
            if (res.code == 200) {
              this.$message.success("保存成功!");
              this.isChangeReceivable = false;
            } else {
              if (null != res.message) {
                this.$message.error(m(res.message));
              } else {
                this.$message.error("系统错误,保存失败!");
              }
            }
          },
          error => {
            console.log(error);
          }
        );
      } else {
        this.isChangeReceivable = true;
      }
    },
    changePayable() {
      if (this.isChangePayable) {
        this.allocationWaybillMegerPay();
      } else {
        this.isChangePayable = true;
      }
    },

    checkRule(e, i) {
      if (!e.serCusId) {
        this.$message.error(`请填写第${i}公司名`);
        return false;
      } else if (!e.costName) {
        this.$message.error(`请填写第${i}费用名称`);
        return false;
      } else if (e.configPayTypec === "C3" && !e.responsibleId) {
        this.$message.error(`请填写第${i}责任人`);
        return false;
      } else if (!e.count) {
        this.$message.error(`请填写第${i}数量`);
        return false;
      } else if (!e.currency) {
        this.$message.error(`请填写第${i}币种`);
        return false;
      } else if (!e.unitPrice) {
        this.$message.error(`请填写第${i}单价`);
        return false;
      } else if (!e.billType) {
        this.$message.error(`请填写第${i}账单类型`);
        return false;
      }

      return true;
    },

    submitUpload() {
      this.$refs.upload.submit();
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handlePreview(file) {
      console.log(file);
    },
    lazyloadWaybillReceivePayables() {
      this.fullscreenLoading = true;
      var param = {};
      //直接从缓存获取
      const waybillId = this.$route.query.waybillId;
      param["id"] = waybillId;
      ajax("initWaybillMergeReceiveAndPay", param).then(
        res => {
          this.fullscreenLoading = false;
          console.log("加载应收应付数据", res);
          if (res.code == 200) {
            this.templateOptions.currencyOptions = res.data["currencyMap"];
            this.templateOptions.configPayNameOptions =
              res.data["configPayNameMap"];
            this.templateOptions.configPayTypeOptions =
              res.data["configPayTypeMap"];
            this.templateOptions.userOptions = res.data["userMap"];
            this.templateOptions.companyOptions = res.data["customerMap"];
            this.templateOptions.serviceOptions = res.data["serviceCompanyMap"];
            this.templateOptions.payNameTypeMap = res.data["payNameTypeMap"];
            this.receivableData = res.data["receives"];
            this.payableData = res.data["pays"];
            this.receiveTotalCost = res.data["receiveTotalCost"];
            this.payTotalCost = res.data["payTotalCost"];
            this.shippingWay = res.data["shippingWay"];
            this.totalProfit = res.data["totalProfit"];
            this.totalProfitD = res.data["totalProfitD"];
            this.profit = res.data["profit"];
            this.payMap = res.data["payMap"];
            this.parseServicerMap = res.data["parseServicerMap"];
            this.receiveMap = res.data["receiveMap"];
            this.mergePayMap = res.data["mergePayMap"];
            this.optUser = res.data["optUser"];
            this.collectMap = res.data["collectMap"]; //末端显示用
            this.totalexpressweight = res.data["totalexpressweight"];

            if (
              res.data.waybillMergePayLumps &&
              res.data.waybillMergePayLumps.length > 0
            ) {
              let l = [];
              for (const i of res.data.waybillMergePayLumps) {
                const obj = {
                  waybillNoList: i.waybillNos,
                  HNumber: i.waybillSingleNos,
                  lumpName: i.lumpName,
                  tableData: []
                };

                for (const j of i.mergePays) {
                  for (const e of this.payableData) {
                    if (e.id == j.id) {
                      e.lumpName = i.lumpName;
                      e.selectStatus = true;
                      e.disabled = true;
                      obj.tableData.push(e);
                    }
                  }
                }
                l.push(obj);
              }
              this.singleList = l;
            }

            let arr = [];

            for (const k in res.data.singleMap) {
              const obj = {
                waybillNo: k == "null" ? "-" : k,
                children: res.data.singleMap[k]
              };

              if (res.data.singleMap[k]) {
                res.data.singleMap[k].forEach(singlelistone => {
                  if (
                    singlelistone &&
                    (singlelistone.isCustomerDeclaration === 1 ||
                      singlelistone.isCustomerDeclaration === 42)
                  ) {
                    this.declarations.push(singlelistone.waybillNo);
                    this.declarationMap[singlelistone.id] =
                      singlelistone.waybillNo;
                  }
                });
              }
              console.log("当前报关运单:", this.declarationMap);
              console.log("obj :>> ", obj);
              arr.push(obj);
            }

            for (const [i, e] of arr.entries()) {
              e.key = i + 1;
              e.isChild = false;
              e.isSel = false;
              e.version = i;
              for (const [j, m] of e.children.entries()) {
                // console.log("j,m :>> ", j, m);
                m.key = (i + 1) * 1000 + j;
                m.isChild = true;
                m.isSel = false;
                m.version = i;
              }
            }

            console.log("singleMap :>> ", arr);

            this.singleMap = arr;
            //加载完才显示操作按钮
            this.loadingOver = true;
            setTimeout(() => {
              this.initTbale();
            }, 1000);
          }
        },
        error => {
          console.log(error);
          this.fullscreenLoading = false;
        }
      );
    },

    initTbale() {
      console.log(
        "this.$refs.hotTable :>> ",
        this.$refs.hotTable.$refs.hotTable
      );
      console.log('this.payableData :>> ', this.payableData);
      const td = this.$refs.hotTable.$el.children[1].children[0].children[0]
        .children[0].children[0].children[0].children[2].children;
      for (const [i, e] of this.payableData.entries()) {
        if (e.selectStatus) {
          td[i].children[0].children[0].setAttribute("disabled", true);
          e.disabled = true;
        }
      }

      this.fullscreenLoading = false;
    },
    // 获取销账日期
    async getBillingDate(scope, type) {
      // 存在数据
      if (scope.row.billingDate) {
        return;
      }

      // 请求数据
      const data = ajax("", {});

      this.$set(scope.row, "billingDate", data);
    },
    handleAllSelection(a, b, c) {
      console.log(a, b, c);
    },
    handleSelectionChange2(val, row) {
      console.log('handleSelectionChange2',this.selectedList);
      let selectedList = this.selectedList,
        tableData = this.singleMap;
      // console.log("selectedList :>> ", selectedList);
      // console.log("tableData :>> ", tableData);
      // 如果点击的子节点
      if (row.isChild) {
        if (row.isSel) {
          // selectedList.findIndex(ele => ele.key === row.key)
          console.log("selectedList :>> ", selectedList);
          const index = selectedList.findIndex(x => x.id === row.id);
          selectedList.splice(index, 1);
        } else {
          selectedList.push(row);
        }
        // 判断多少条是被选中的
        let cLength = selectedList.filter(ele => ele.key == row.key).length;
        // console.log("cLength :>> ", cLength);
        // console.log("row :>> ", row);
        // 查找当前子节点的父节点
        let pNode = tableData.find(ele => ele.version == row.version);
        // console.log(pNode);
        // 如果长度相同那就打钩，不同则取消
        this.$refs.selectTable.toggleRowSelection(
          pNode,
          cLength === pNode.children.length
        );
        pNode.isSel = cLength === pNode.children.length;
      } else {
        // 点击父节点
        //  数据操作  如果是已被勾选那么删除此列所有数据
        if (row.isSel) {
          let delList = selectedList.filter(ele => ele.key === row.key);
          for (const item of delList) {
            item.isSel = false;
            console.log("item :>> ", item);
            console.log("selectedList :>> ", selectedList);
            // selectedList.remove(item);
            const index = selectedList.findIndex(x => x.id === item.id);
            selectedList.splice(index, 1);
          }
          // console.log("remove");
        } else {
          // console.log("push");
          // 否则是新增
          for (const item of row.children) {
            if (selectedList.indexOf(item) == -1) {
              item.isSel = true;
              selectedList.push(item);
            }
          }
        }
        row.children.forEach(ele2 => {
          this.$refs.selectTable.toggleRowSelection(ele2, !row.isSel);
        });
      }
      row.isSel = !row.isSel;
    },
    S4() {
      return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
    },
    guid() {
      return (
        this.S4() +
        this.S4() +
        this.S4() +
        this.S4() +
        this.S4() +
        this.S4() +
        this.S4() +
        this.S4()
      );
    }
  },
  created: function() {
    this.action =
      constant.API_SERVER +
      "/api/consume/upload?uri=" +
      untransform(this.$route.params.uri) +
      "&f=imporWaybillPayFeePdf&type=blank&name=sub";
  },
  mounted() {
    this.lazyloadWaybillReceivePayables();
  }
};
</script>

<style lang="scss" scoped>
.border-lr {
  border-left: 1px solid #ccc;
  border-right: 1px solid #ccc;
}
/deep/ .el-date-editor.el-input,
.el-date-editor.el-input__inner {
  width: 100%;
}
</style>
<style>
.handsontable th {
  background: #fff;
  color: #2c3e50;
  text-align: left;
  font-weight: bold;
}

.el-card__body {
  color: #606266;
}
.handsontable th:first-child,
.handsontable th:nth-child(2),
.handsontable td:first-of-type,
.handsontable tr th,
.handsontable tr td,
.handsontable tr:first-child th,
.handsontable tr:first-child td {
  border-color: #ebeef5;
}
</style>
